const BASE_API = {
	VITE_APP_API_BASEURL: "https://api-test.jinzhuangli.com",
	VITE_APP_CAS_BASE_URL: "https://static-test.jinzhuangli.com",
	VITE_APP_CAS_STATIC_BASE_URL: "https://static-test.jinzhuangli.com/staticFile/images/"
};

// 预览图片
/**
 *
 * @param avatar 图片路径
 * @param compress 图片是否压缩
 */
export function getImgView(avatar: string | undefined, compress: boolean = false) {
	let subStr: string = "http";
	let locationStr: string = "blob";
	let compressVariant: string = "?x-oss-process=image/resize,w_800";
	if (avatar && (avatar.startsWith(subStr) || avatar.startsWith(locationStr))) {
		return compress ? avatar + compressVariant : avatar;
	} else if (avatar && avatar.length > 0 && avatar.indexOf("[") == -1) {
		return compress ? BASE_API.VITE_APP_CAS_BASE_URL + "/" + avatar + compressVariant : BASE_API.VITE_APP_CAS_BASE_URL + "/" + avatar;
	}
}

/**
 * 数字转化成大写字母
 * @param num 数字
 * @param ascll 大写还是小写 64 为大写 96 为小写
 * @return 大写字母
 */
export function numToUpperCaseLetters(num: number, ascll: number = 64) {
	if (num < 1 || num > 26) {
		console.error("数字范围为 1 - 26");
		return "";
	}
	const upperCaseLetter = String.fromCharCode(num + ascll);
	return upperCaseLetter;
}

/**
 * 获取静态文件路径
 * @param name 文件名称
 * @param type 文件类型 false 静态文件 true上传文件
 */
export function getFileUrl(name: string, type: boolean = false) {
	if (!name) return "";
	if (name.indexOf("http") != -1) return name;
	if (name.indexOf("https") != -1) return name;
	name.indexOf(".") === -1 ? (name += ".png") : "";
	return type ? BASE_API.VITE_APP_CAS_BASE_URL + "/" + name : BASE_API.VITE_APP_CAS_STATIC_BASE_URL + name;
}

/**
 * 获取元素信息
 * @param {String | Array} element 元素名
 * @param {Object} that  vm实例
 * @return {Object} 返回元素信息
 */
export function getEleInfo(element: string | string[], that: any): any {
	return new Promise((resolve, reject) => {
		let query = uni.createSelectorQuery().in(that);
		setTimeout(async () => {
			if (Array.isArray(element)) {
				for (let i = 0; i < element.length; i++) {
					await query.select(element[i]).boundingClientRect();
				}
			} else {
				query.select(element).boundingClientRect();
			}
			query.exec((res) => {
				if (!res || !res[0]) {
					reject(res);
				}
				if (res.length == 1) {
					resolve(res[0]);
				} else {
					resolve(res);
				}
			});
		});
	});
}

/**
 * 复制文本
 * @param {any} data
 * @param {any} msg
 * @return
 */
export function copyFn(data: string, msg: string = "复制成功") {
	return new Promise((resolve, reject) => {
		uni.setClipboardData({
			data,
			success() {
				uni.showToast({
					title: msg,
					icon: "none"
				});
				resolve(void 0);
			},
			fail(e) {
				console.error("copy error===>", e);
				reject();
			}
		});
	});
}

/**
 * 时间戳转YYYY-MM-DD hh:mm:ss
 * @param {any} timestamp
 * @return
 */
export function formatTimestamp(timestamp: number) {
	const date = new Date(timestamp);
	const year = date.getFullYear();
	const month = String(date.getMonth() + 1).padStart(2, "0");
	const day = String(date.getDate()).padStart(2, "0");
	const hours = String(date.getHours()).padStart(2, "0");
	const minutes = String(date.getMinutes()).padStart(2, "0");
	const seconds = String(date.getSeconds()).padStart(2, "0");

	return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

export function parseQueryString(str: string) {
	str = decodeURIComponent(str);
	// 创建一个空对象
	var obj = {};

	// 使用正则表达式匹配字符串中的键值对
	var regex = /([^&=]+)=([^&]*)/g;
	var match;

	// 遍历匹配结果，并将键值对存入对象中
	while ((match = regex.exec(str))) {
		obj[decodeURIComponent(match[1])] = decodeURIComponent(match[2]);
	}

	return obj;
}

// 规格
export interface SkuItem {
	id: string; // SKU ID
	ids: string; // 其他 ID
	originIds: string;
	measurementOfMeasurementUnit: string; // 计量单位的计量单位
	minOrderQuantity: number; // 最小订购数量
	minOrderUnitPrice: number; // 最小订购单价
	purchaseNumber: number; // 购买数量
	quantityOfMeasurement: number; // 计量数量
	quantityOfMeasurementOfMeasurement: number; // 计量数量的计量单位
	sidCombination: string; // 组合 ID
	skuNumber: string; // SKU 编号
	skuPic: string; // SKU 图片
	skus: any; // SKU 列表
	suggestedSellingPrice: number; // 建议售价
	unit: string; // 单位
	unitOfMeasurement: string; // 计量单位
	actualSellingPrice: number; // 实际售价
	factoryPrice: number; // 工厂价格
	productId: string;
	skuTxt: string;
	supplyPrice: number | undefined;
}
/**
 * 整合规格数据
 * @param skuList
 * @returns
 */
export function convertSkuListToStandardSortList(skuList: SkuItem[]) {
	const result: any = {};
	// 提取所有属性
	skuList.forEach((sku) => {
		sku.skus.forEach((item: any) => {
			if (!result[item.k_id]) {
				result[item.k_id] = {
					id: item.k_id,
					productId: sku.productId,
					name: item.k,
					value: item.k,
					selectId: "",
					leaf: []
				};
			}
			// 检查是否已经存在相同的叶子节点
			const existingLeaf = result[item.k_id].leaf.find((leaf: any) => leaf.id === item.v_id);
			if (!existingLeaf) {
				result[item.k_id].leaf.push({
					id: item.v_id,
					productId: sku.productId,
					sid: item.k_id,
					value: item.v,
					detailName: item.v,
					coverImg: item.v_cover || ""
				});
				result[item.k_id].hasCover = result[item.k_id].leaf.some((c: any) => c.coverImg);
			}
		});
	});
	return Object.values(result);
}

/**
 * 数字小数位格式化
 * @param value 需要转化的数字
 * @param count 保留的小数位
 * @returns
 */
export const toFixed = (value: number | string, count = 2) => {
	let val = typeof value === "number" ? value : Number(value);
	if (isNaN(val)) return 0;
	return Number(val.toFixed(count));
};

// 获取url参数
export function GetRequest(link?: string) {
	if (link && link.indexOf("?") != -1) {
		link = link.substring(link.indexOf("?"));
	}
	const url = decodeURIComponent(link || location.search); //获取url中"?"符后的字串
	let theRequest = new Object();
	if (url.indexOf("?") != -1) {
		let str = url.substr(1);
		let arr = str.split("&");
		for (let i = 0; i < arr.length; i++) {
			theRequest[arr[i].split("=")[0]] = unescape(arr[i].split("=")[1]);
		}
	}
	return theRequest;
}

// 文件下载
export const downloadFile = (url) => {
	uni.showLoading({
		title: "下载中..."
	});

	uni.downloadFile({
		url: url, //仅为示例，并非真实的资源
		success: (res) => {
			uni.saveFile({
				tempFilePath: res.tempFilePath,
				success: (res) => {
					uni.hideLoading();
					uni.showToast({
						title: `下载成功,文件保存到：${res.savedFilePath}`,
						icon: "none"
					});
				},
				fail: (err) => {
					uni.hideLoading();
					uni.showToast({
						title: err,
						icon: "none"
					});
				}
			});
		},
		fail: (err) => {
			uni.hideLoading();
			uni.showToast({
				title: err,
				icon: "none"
			});
		}
	});
};

// 文件查看
export const previewFile = (url) => {
	uni.showLoading({
		title: "加载中..."
	});

	uni.downloadFile({
		url: url, //仅为示例，并非真实的资源
		success: (res) => {
			uni.openDocument({
				filePath: res.tempFilePath,
				success: () => {
					uni.hideLoading();
				},
				fail: (err) => {
					uni.hideLoading();
					uni.showToast({
						title: err,
						icon: "none"
					});
				}
			});
		}
	});
};

// 复制文本
export const copyText = (text: string, title: string = "复制成功") => {
	uni.setClipboardData({
		data: text,
		success: function () {
			uni.showToast({
				title,
				icon: "none"
			});
		}
	});
};
